<?php
namespace app\admin\controller;
use app\model\UserDiscount as UserDiscountModel;
use think\Db;


class UserDiscount extends Base
{
    public function __construct(){
        $model = new UserDiscountModel();
        $this->model = $model;
        parent::__construct();
        
        $page_info = $this->page_info;
        $page_info['title'] = '用户折扣';

        $this->assign([
            'model'=>$this->model,
            'page_info'=>$page_info
        ]);
    }

    public function assignFields(){
        $users = Db::name('user')->field('id,name')->select();
        $users  = arrayParamExtract($users ,'id','name');

        $tmp_products = Db::name('product')->field('code,name')->select();
        $products = [];
        foreach ($tmp_products as $k => $vo) {
            $products[$vo['code']] = $vo['name'].'（'.$vo['code'].'）';
        }

        $fields = [
            'user_id'=>['name'=>'用户','type'=>'select2','params'=>$users],
            'product'=>['name'=>'产品','type'=>'select2','params'=>$products],
            'discount'=>['name'=>'折扣（小数表示，如：7折为0.7）','type'=>'text']
        ];
        $valids = createPageValid($fields);
        $this->assign([
            'fields'=>$fields,
            'valids'=>$valids
        ]);
    }

    public function index(){
        $model = $this->model;
        $map_params = [
            ['key'=>'user_id','type'=>'='],
            ['key'=>'product','type'=>'=']
        ];
        $map = getSearchParam($map_params);

        $users = Db::name('user')->field('id,name')->select();
        $users  = arrayParamExtract($users ,'id','name');

        $tmp_products = Db::name('product')->field('code,name')->select();
        $products = [];
        foreach ($tmp_products as $k => $vo) {
            $products[$vo['code']] = $vo['name'].'（'.$vo['code'].'）';
        }
        $search_params = [
            [
                ['key'=>'user_id','name'=>'用户','type'=>'select2_1','params'=>$users],
                ['key'=>'product','name'=>'产品','type'=>'select2_1','params'=>$products] 
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);

        $page_param = [
            'page'=>input('page',1),
            'list_rows'=>input('page_size',20)
        ];
        $list = $model->where($map)->order('id','desc')->paginate($page_param);
        $page = $list->render();

        $list = $list->toarray();
        foreach ($list['data'] as $k => $vo) {
            $list['data'][$k]['user_name'] = Db::name('user')->where('id',$vo['user_id'])->value('name');
            $list['data'][$k]['product_name'] = Db::name('product')->where('code',$vo['product'])->value('name');
        }
        return view('index', [
            'list'=>$list,
            'page'=>$page
        ]);
    }

    public function add(){
        if (request()->isPost()) {
            $fields = [
                'must'=>['user_id','product','discount']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
            if ($save_data['discount'] < 0 || $save_data['discount'] > 1) {
                $this->error('折扣值需在0~1之间');
            }
            // 检测折扣是否符合
            $this->checkDiscount($save_data['user_id'],$save_data['product'],$save_data['discount']);
        }
        return parent::saveData($save_data);
    }

    public function edit(){
        $id = input('id');
        if (empty($id)) { $this->error('id不能为空'); }
        
        if (request()->isPost()) {
            $fields = [
                'must'=>['discount','user_id','product']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
            if ($save_data['discount'] < 0 || $save_data['discount'] > 1) {
                $this->error('折扣值需在0~1之间');
            }

            // 检测折扣是否符合
            $this->checkDiscount($save_data['user_id'],$save_data['product'],$save_data['discount']);
        }
        return parent::updateData($id,$save_data);
    }


    public function moreEdit($user_id){
        $user = Db::name('user')->where('id',$user_id)->find();

        $map_params = [
            ['key'=>'name','type'=>'like'],
            ['key'=>'code','type'=>'like'],
            ['key'=>'category_id','type'=>'=']
        ];
        $map = getSearchParam($map_params);

        $categorys = Db::name('category')->field('id,name')->order('sort desc,id asc')->select();
        $categorys = arrayParamExtract($categorys,'id','name');
        $search_params = [
            [
                ['key'=>'name','name'=>'名称','type'=>'text'],
                ['key'=>'code','name'=>'产品代码','type'=>'text'],
                ['key'=>'category_id','name'=>'分类','type'=>'select1_1','params'=>$categorys] 
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);
        $list = Db::name('product')->alias('p')->field('p.name,p.code,p.discount as product_discount,ud.discount')
        ->join('(select * from '.config('database.prefix').'user_discount where user_id = '.$user_id.') ud','p.code = ud.product','left')
        ->where($map)->order('discount desc,sort desc,p.id asc')->select();
        return view('moreEdit', [
            'user'=>$user,
            'list'=>$list
        ]);
    }

    public function updateDiscount(){
        $model = $this->model;
        $fields = [
            'must'=>['user_id','product','discount']
        ];
        $params = paramFilter(request()->param(),$fields);
        if (!empty($params['error_msg'])) {
            return ['status'=>0,'msg'=>$params['error_msg']];
        }
        if ($params['discount'] < 0 || $params['discount'] > 1) {
            $this->error('折扣值需在0~1之间');
        }
        // 检测折扣是否符合
        $this->checkDiscount($params['user_id'],$params['product'],$params['discount']);

        $map = [
            ['user_id','=',$params['user_id']],
            ['product','=',$params['product']]
        ];
        if ( $model->where($map)->count() > 0 ) {
            if ( !$model->where($map)->update(['discount'=>$params['discount']]) ) {
                return ['status'=>0,'msg'=>'保存失败，请检查折扣数值'];
            }
        }else{
            $params['ctime'] = time();
            if ( !$model->insert($params) ) {
                return ['status'=>0,'msg'=>'保存失败，请检查折扣数值'];
            }
        }
        return ['status'=>1,'discount'=>$model->where($map)->value('discount')];
    }

    public function update(){
        $model = $this->model;
        $fields = [
            'must'=>['discount']
        ];
        $save_data = paramFilter(request()->param(),$fields);
        if (!empty($save_data['error_msg'])) {
            return ['status'=>0,'msg'=>$save_data['error_msg']];
        }
        if ($save_data['discount'] < 0 || $save_data['discount'] > 1) {
            $this->error('折扣值需在0~1之间');
        }

        $ids = explode(',', input('id'));
        foreach ($ids as $id) {
            $params = $model->where('id',$id)->find();
            // 检测折扣是否符合
            $this->checkDiscount($params['user_id'],$params['product'],$save_data['discount']);
        }
        
        if ( $model->where('id','in',$ids)->update($save_data) !== false ) {
            $this->success("编辑成功");
        }else{
            $this->error("编辑失败");
        }
    }

    public function moreUpdate(){
        $model = $this->model;
        $fields = [
            'must'=>['discount','user_id']
        ];
        $save_data = paramFilter(request()->param(),$fields);
        if (!empty($save_data['error_msg'])) {
            $this->error($save_data['error_msg']);
        }
        if ($save_data['discount'] < 0 || $save_data['discount'] > 1) {
            $this->error('折扣值需在0~1之间');
        }
        $codes = explode(',', input('code'));
        foreach ($codes as $code) {
            // 检测折扣是否符合
            $this->checkDiscount($save_data['user_id'],$code,$save_data['discount']);
        }

        Db::startTrans();
        try{
            foreach ($codes as $code) {
                $map = [
                    ['user_id','=',$save_data['user_id']],
                    ['product','=',$code]
                ];
                if ( $model->where($map)->count() > 0 ) {
                    if ( $model->where($map)->update(['discount'=>$save_data['discount']]) === false ) {
                        throw new \Exception("保存失败，请检查折扣数值".$code."（".$save_data['discount']."）");
                    }
                }else{
                    $params = $save_data;
                    $params['product'] = $code;
                    $params['ctime'] = time();
                    if ( !$model->insert($params) ) {
                        throw new \Exception("保存失败，请检查折扣数值".$code."（".$params['discount']."）");
                    }
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("编辑成功");
    }

    // 检测折扣是否符合
    public function checkDiscount($user_id,$product,$discount){
        if ($discount < 0.3 || $discount > 1) {
            $this->error('用户折扣需要再0.3~1之间（包含）');   
        }
        // 判断是否超过所属销售的折扣
        $admin_id = Db::name('user')->where('id',$user_id)->value('admin_id');
        if (!empty($admin_id)) {
            $check_discount = Db::name('admin_discount')->where([
                ['product','=',$product],
                ['admin_id','=',$admin_id]
            ])->value('discount');
            if (empty($check_discount)) {
                $check_discount = Db::name('admin')->where('id',$admin_id)->value('total_discount');
            }
            // if ($discount < $check_discount) {
            //     $this->error($product.'折扣不能低于管理员折扣');
            // }
        }
        // 判断是否超过平台的折扣
        $check_discount = Db::name('product')->where('code',$product)->value('discount');
        if ($discount < $check_discount) {
            $this->error($product.'折扣不能低于平台折扣');
        }
        return true;
    }

    public function import(){
        set_time_limit ( 0 );
        ini_set('memory_limit','1024M');
   
        $model = $this->model;
        if (request()->isPost()) {
            $user_id = input('user_id');
            if (empty($user_id)) {
                $this->error('请选择用户');
            }

            $file = $_FILES['file'];
            if (empty($file) || empty($file['name'])) {
                $this->error('未检测到文件');
            }
            $extension = strtolower(pathinfo($file['name'],PATHINFO_EXTENSION));
            if ($extension =='xlsx') {
                $objReader = new \PHPExcel_Reader_Excel2007();
                $objExcel = $objReader->load($file['tmp_name']);
            } else if ($extension =='xls') {
                $objReader = new \PHPExcel_Reader_Excel5();
                $objExcel = $objReader->load($file['tmp_name']);
            }

            $list=$objExcel->getsheet(0)->toArray();   //转换为数组格式
            array_shift($list);  //删除第一个数组(标题);

            $product_codes = Db::name('product')->column('code');
            $ctime = time();
                
            $result = [];
            foreach ($list as $k => $vo) {
                $tmp = ['status'=>1];
                Db::startTrans();
                try{
                    $data = [
                        'user_id'=>$user_id,
                        'product'=>strtolower(trim($vo[0])),
                        'discount'=>$vo[1],
                        'ctime'=>$ctime
                    ];

                    $tmp['name'] = $data['product'];
                    $tmp['discount'] = $data['discount'];

                    if (!in_array($data['product'],$product_codes)) {
                        throw new \Exception("产品编码不存在");  
                    }

                    if ($data['discount'] < 0.3 || $data['discount'] > 1) {
                        throw new \Exception("用户折扣需要再0.3~1之间（包含）");  
                    }

                    if ( Db::name('user_discount')->where([
                        ['user_id','=',$user_id],
                        ['product','=',$data['product']]
                    ])->count() > 0 ) {
                        throw new \Exception("用户当前产品已设置折扣");  
                    }

                    Db::name('user_discount')->insert($data);
                    // 更新成功 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 更新失败 回滚事务
                    Db::rollback();
                    $tmp['status'] = 0;
                    $tmp['msg'] = $e->getMessage();
                }

                $result[] = $tmp;
            }
            $this->assign([
                'result'=>$result
            ]);
        }

        $users = Db::name('user')->select();
        return view('import', [
            'users'=>$users
        ]);
    }
   
}
